import json
from datetime import datetime

from django.utils import timezone
from django.views import View
from django.http import JsonResponse

from homes.models import House
from order.models import Order
from users.utils import LoginRequiredJSONMixin
from users.views import logger
from django.db import transaction


class CreateOrdersView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 提取参数
        data = json.loads(request.body.decode())
        house_id = data.get('house_id')
        start_date = data.get('start_date')
        end_date = data.get('end_date')
        start_date = datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.strptime(end_date, '%Y-%m-%d')
        # 入住天数
        diff = end_date - start_date
        if diff.days == 0:
            days = 1
        else:
            days = diff.days

        # 校验
        if not all([house_id, start_date, end_date]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': '缺少重要参数',
            })

        user = request.user
        house = House.objects.get(pk=house_id)
        if house.user_id == user.id:
            return JsonResponse({
                'errno': 4004,
                'errmsg': '用户身份信息冲突'
            })
        # 总金额
        house_price = house.price
        amount = house.price * days
        order_id = timezone.localtime().strftime('%y%m%d%H%M%S') + ('%09d' % user.id)

        try:
            order = Order.objects.create(
                order_id=order_id,
                user_id=user.id,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                house_price=house.price,
                days=days,
                amount=amount,
                status=Order.ORDER_STATUS.get('WAIT_ACCEPT')
            )
        except Order.DoesNotExist as e:
            logger.error(e)
            return JsonResponse({
                'errno': 4004,
                'errmsg': '数据错误'
            })

        return JsonResponse({
            "errno": "0",
            "errmsg": "下单成功",
            'order_id': order.order_id
        })
    # 获取订单
    def get(self, request):
        role = request.GET.get('role')
        if not role:
            return JsonResponse({'errno': 4103, 'errmsg': '缺少重要参数'})
        if role == 'landlord':
            user = request.user
            order_objs = Order.objects.filter(house__user__id=user.id)
            # user = User.objects.get(id=user.id)
            # houses = House.objects.filter(user=user)
            # order_list = []
            # for house in houses:
            #     orders = Order.objects.filter(house=house)
            #     if orders:
            #         for order in orders:
            #             order_list.append(order)
        elif role == 'custom':
            user = request.user
            # print(user.id)
            order_objs = Order.objects.filter(user_id=user.id)
        else:
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})
        if not order_objs:
            return JsonResponse({'errno': 4002, 'errmsg': '无订单信息'})
        orders_list = []
        for order in order_objs:
            orders_list.append({
                "order_id": order.order_id,
                "amount": order.amount,
                "comment": order.comment,
                "ctime": str(order.create_time).split(' ')[0],
                "days": order.days,
                "end_date": str(order.end_date).split(' ')[0],
                "img_url": order.house.index_image_url.url,
                "start_date": str(order.begin_date).split(' ')[0],
                "status": Order.ORDER_STATUS_ENUM[order.status],
                "title": order.house.title
            })
        return JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': {'orders': orders_list}})


# 接单和拒单
class OrderStatusView(LoginRequiredJSONMixin, View):
    def put(self, request, order_id):
        data = json.loads(request.body.decode())
        action = data.get('action')
        reason = data.get('reason')
        if not action:
            return JsonResponse({
                'errno': 4103,
                'errmsg': '缺少重要参数',
            })
        if action == 'accept':
            # try:
            #     order = Order.objects.get(pk=order_id,status=Order.ORDER_STATUS['WAIT_ACCEPT'])
            # except Order.DoesNotExist as e:
            #     logger.error(e)
            #     return JsonResponse({
            #         'errno': 4001,
            #         'errmsg': '数据库查询错误'
            #     })
            # try:
            #     house = House.objects.get(pk=order.house.id)
            # except House.DoesNotExist as e:
            #     logger.error(e)
            #     return JsonResponse({
            #         'errno': 4001,
            #         'errmsg': '数据库查询错误'
            #     })
            # try:
            #     house.order_count += 1
            #     house.save()
            #
            #     order.status = Order.ORDER_STATUS['WAIT_PAYMENT']
            #     order.save()
            with transaction.atomic():
                save_id = transaction.savepoint()
                try:
                    order = Order.objects.get(pk=order_id, status=Order.ORDER_STATUS['WAIT_ACCEPT'])
                    house = House.objects.get(pk=order.house.id)
                    house.status = House.HOUSE_STATUS['ALREADY_RESERVED']
                    house.order_count += 1
                    house.save()

                    order.status = Order.ORDER_STATUS['WAIT_PAYMENT']
                    order.save()

                except Order.DoesNotExist as e:
                    logger.error(e)
                    transaction.savepoint_rollback(save_id)
                    return JsonResponse({
                        'errno': 4004,
                        'errmsg': '数据库写入错误'
                    })
            transaction.savepoint_commit(save_id)
        elif action == 'reject':
            try:
                order = Order.objects.get(pk=order_id)
                order.comment = reason
                order.status = Order.ORDER_STATUS['REJECTED']
                order.save()
            except Order.DoesNotExist as e:
                logger.error(e)
                return JsonResponse({
                    'errno': 4004,
                    'errmsg': '数据库写入错误'
                })
        else:
            return JsonResponse({
                'errno': 4004,
                'errmsg': '数据错误'
            })
        return JsonResponse({
            'errno': 0,
            'errmsg': '接单成功'
        })


class CommentView(LoginRequiredJSONMixin, View):
    def put(self, request, order_id):
        comment = json.loads(request.body.decode()).get('comment')
        if not comment:
            return JsonResponse({
                'errno': 4103,
                'errmsg': '缺少重要参数',
            })
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                order = Order.objects.get(pk=order_id)
                order.comment = comment
                order.status = order.ORDER_STATUS['COMPLETE']
                order.save()

                house = House.objects.get(pk=order.house.id)
                house.status = House.HOUSE_STATUS['NOT_SCHEDULED']
                house.save()
            except Exception as e:
                logger.error(e)
                transaction.savepoint_rollback(save_id)
                return JsonResponse({
                    'errno': 4004,
                    'errmsg': '数据库写入错误'
                })
            transaction.savepoint_commit(save_id)

        return JsonResponse({"errno": "0", "errmsg": "评论成功"})
